import React, { useState } from 'react';
import { Form, Modal } from 'antd';
import CodeMirror from '@uiw/react-codemirror';
import { javascript } from '@codemirror/lang-javascript';
import Icon from './../icon/Icon';
import useControlOptions from '../../hooks/useControlOptions';
import { ScriptLoadProps } from './ScriptBefore';
import styles from './style.module.scss';

const FormItem = Form.Item;
const extensions = [javascript({ jsx: true })];

export default () => {
  const { options, changeControlProps: change } = useControlOptions<ScriptLoadProps>();
  const [visible, setVisible] = useState(false);
  const [codeMirrorValue, setCodeMirrorValue] = useState('');

  function show() {
    setVisible(true);
    setCodeMirrorValue(options.scriptText || '');
  }

  function onOk() {
    setVisible(false);
    change('scriptText', codeMirrorValue);
    setCodeMirrorValue('');
  }

  function onCancel() {
    setVisible(false);
    setCodeMirrorValue('');
  }

  return (
    <>
      <FormItem label='脚本内容'>
        <CodeMirror
          extensions={extensions}
          onChange={(value: string) => change('scriptText', value)}
          value={options.scriptText} />
      </FormItem>
      <Icon
        className={styles.screenIcon}
        icon='&#xe67c;'
        onClick={show} />
      <Modal
        visible={visible}
        title='脚本'
        width={1000}
        onCancel={onCancel}
        onOk={onOk}>
        <CodeMirror
          extensions={extensions}
          onChange={setCodeMirrorValue}
          value={codeMirrorValue} />
      </Modal>
    </>
  )
}